package 中等;

import java.util.Stack;

public class 字符串转换整数 {
    public static void main(String[] args) {
        String s ="10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000522545459";
        System.out.println(myAtoi(s));

    }

    public static int myAtoi(String s) {
        int len = s.length();
        if (len <1){
            return 0;
        }
        Stack<Character> stack = new Stack<>();
        boolean flag = false;
        for (int i = 0; i < len; i++) {
            char c = s.charAt(i);
            if(!flag){
                if (c =='-'||c =='+' ||(48<= c && c <=57)||c==' '){
                    if (c!= ' '){
                        flag = true;
                        stack.push(c);
                    }
                }else {
                    return 0;
                }
            }else {
                if (48<= c && c <=57){
                    stack.push(c);
                }else {
                    break;
                }
            }
        }
        Long result = 0L;
        Long x = 1L;
        while (!stack.empty()){
            Character pop = stack.pop();
            if (pop=='-'){
                result = -result;
            }else if (pop=='+'){

            }else {
                if (result-1!=Integer.MAX_VALUE){
                    result += (pop-48)*x;
                    if (x*10>0){
                        x *= 10;
                    }
                    if (result<0){
                        result  = (long)Integer.MAX_VALUE;
                        result += 1;
                    }
                }
            }
        }
        if (result<Integer.MIN_VALUE){
            return Integer.MIN_VALUE;
        }else if (result>Integer.MAX_VALUE){
            return Integer.MAX_VALUE;
        }
        return result.intValue();

    }
}
